<?php

namespace App\Services\BuyVip;

use App\Models\User;
use Carbon\Carbon;
use App\Models\Address;
use App\Models\VipCategory;
use App\Models\VipWelfareDetail;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class BuyVipRequest extends FormRequest
{
	public function rules()
	{
		$addressId =  (int)request('address_id');
		if ($addressId) {
			$this->address = Address::find($addressId);
		}
		return [
			'address_id' => ['required', $this->address()],
			'vip_category_id' => [
				'required',
				'integer',
				'min:1',
				$this->vipCategory(),
			],
			'items' => 'required|array',
			'items.*.welfare_detail_id' => $this->welfare(),

		];
	}

	public function vipCategory()
	{
		return function ($key, $value, $fail) {

			if (!VipCategory::find($this->vip_category_id)) {
				return $fail('vip类型不存在');
			}

			return true;
		};
	}

	public function address()
	{
		return function ($attribute, $value, $fail) {
			if (!$this->address) {
				return $fail('地址不存在');
			}
			return true;
		};
	}

	protected function welfare()
	{
		return [
			'integer',
			function ($attribute, $value, $fail) {
				if ($value) {
					if(!$welfare = VipWelfareDetail::find($value)){
						return $fail('福利类型不存在');
					}
					
				} 
				
				return true;
			}
		];
	}
	

	public function getAddress(): Address
	{
		return $this->address;
	}
}
